using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using TicTacToe;

namespace TicTacToe.Opponents
{
    [Opponent]
    public class BlockingOpponent : IOpponent
    {
        public string Name { get { return "Blocking Opponent"; } }
        public string Description { get { return "Not the brightest, but will complete its own lines and block if you threaten to win."; } }

        /// <summary>
        /// The blocking opponent chooses its move as follows:
        /// 1) If: there is a line with only a single space, 
        ///        and the other values on that line all match,
        ///        It will complete that line. This either wins the game, or prevents the player from winning.
        /// 2) If there are no such spaces on the board, it will pick at cell at random.
        /// </summary>
        public Point ChooseMove(Board board)
        {
            if (board.IsFull())
                throw new ArgumentException("Unable to make a move because the board is full.");
            
            var lineToFill = board.GetAllScoringCellLines().Where(c => c.HasOneSpace()).FirstOrDefault(c => c.AllPopulatedCellsMatch());

            if (lineToFill != null)
            {
                return lineToFill.Single(cell => !cell.Symbol.HasValue).Position;
            }

            return OpponentHelpers.PickRandomEmptySpace(board);
        }


    }
}